package player

import (
	"fmt"
	"github.com/name5566/leaf/log"
	"go.mongodb.org/mongo-driver/bson"
	"server/cfg"
	db2 "server/db"
	"server/game/activity"
	"server/game/bag"
	"server/game/card"
	"server/msg/jsonData"
	"server/util"
	"strconv"
)

type PlayerLogic struct {
	dao *PlayerDao
}

func NewPlayerLogic() *PlayerLogic {
	return &PlayerLogic{
		dao: NewPlayerDao(),
	}
}
func (p *PlayerLogic) getPlayerListFromDatabase(arrUid []string) ([]Player, error) {
	return p.dao.getPlayerListFromDatabase(arrUid)
}
func (p *PlayerLogic) getPlayerFromDatabase(userId string, key string) (Player, error) {
	return p.dao.getPlayerFromDatabase(userId, key)
}
func (p *PlayerLogic) createPlayer(playerReq *jsonData.MsgCreatePlayerReq) (Player, error) {
	// 从参数中获取消息体
	playerCheck, err := p.dao.getPlayerFromDatabase(playerReq.PlatformId, "pid")
	if err == nil || playerCheck.UID != "" {
		log.Error("Failed to create player to database: %v", err)
		return playerCheck, fmt.Errorf("不能重复创建用户")
	}
	player := Player{
		Level:               1,
		Pid:                 playerReq.PlatformId,
		PlayerName:          playerReq.PlayerName,
		ZoneInfo:            playerReq.ZoneInfo,
		CharacterAppearance: playerReq.CharacterAppearance,
		VoiceMapping:        playerReq.VoiceMapping,
		Gender:              playerReq.Gender,
		Experience:          playerReq.Experience,
		IdentityLevel:       playerReq.IdentityLevel,
		IncomeSpeed:         playerReq.IncomeSpeed,
		Avatar:              DecorativeItem(playerReq.Avatar),
		Title:               DecorativeItem(playerReq.Title),
		Vip:                 VipInit,
		VipDianShu:          VipDianShu,
	}
	shouChongConfig := cfg.ConfigData.TbRechargeShop.GetDataList()
	for _, config := range shouChongConfig {
		if config.FirstreturnIngots != "" {
			var shouChong = ShouChong{
				DangWei:     int(config.Id),
				IsShouChong: false,
			}
			player.ShouChongInfo = append(player.ShouChongInfo, shouChong)
		}
	}

	// 此处可以添加逻辑来生成 UID，例如使用 UUID 库
	// 假设使用 github.com/google/uuid 库生成 UID
	// import "github.com/google/uuid"
	player.UID = util.CreateUUid()

	// 模拟将玩家信息存储到数据库或其他存储介质，这里只是打印信息
	log.Debug("Creating player: %v", player)
	_, err = p.dao.insert(player)
	if err != nil {
		return player, err
	}
	bag.EnInitUserItem(player.UID)
	activity.EnInit(player.UID)
	return player, nil
}
func (p *PlayerLogic) getPlayerInfo(platformId string) (Player, error) {
	// 模拟从数据库中获取玩家信息
	return p.dao.getPlayerFromDatabase(platformId, "pid")
}
func (p *PlayerLogic) unLock(userId string, sid int) (Player, error) {
	playerInfo, err := p.dao.getPlayerFromDatabase(userId, "uid")
	if err != nil {
		return playerInfo, err
	}
	for _, id := range playerInfo.Sids.Ids {
		log.Debug("id is %d", id)
		if id == sid {
			log.Error("id is %d已经解锁了s", id)
			return Player{}, fmt.Errorf("已经解锁过了")
		}
	}
	playerInfo.Sids.Ids = append(playerInfo.Sids.Ids, sid)
	err = db2.Db.Update(TBL_USER,
		bson.M{"uid": userId},
		map[string]interface{}{"$set": map[string]interface{}{"sids": playerInfo.Sids}})
	if err != nil {
		return Player{}, err
	}
	return playerInfo, nil
}
func (p *PlayerLogic) upPlayerLevel(userId string) (map[string]interface{}, error) {
	var ret = make(map[string]interface{}, 0)
	playerInfo, err := p.dao.getPlayerFromDatabase(userId, "uid")
	if err != nil {
		return ret, err
	}
	roleLevel := cfg.ConfigData.TbRoleLevel.Get(int32(playerInfo.Level + 1))
	zuanSU, _ := strconv.Atoi(roleLevel.ZhuanSu)
	if int(roleLevel.YueLi) <= playerInfo.Exp && int32(zuanSU) <= GetUserZhuanSun(userId) {
		ret["can_up"] = 1
	}
	ret["card_info"] = make(map[string]interface{}, 0)
	playerInfo.Level = playerInfo.Level + 1
	if roleLevel.Stuff != 0 {
		addCard, err := card.EnAddCard(userId, int64(roleLevel.Stuff))
		if err != nil {
			return nil, err
		}
		ret["card_info"] = addCard
	}
	ret["user_info"] = playerInfo
	return ret, nil
}
func (p *PlayerLogic) getUserZhuanSun(uid string) int32 {
	return 100
}
func (p *PlayerLogic) AddUserCoins(userId string, coins int) {
	player, _ := p.dao.getPlayerFromDatabase(userId, "uid")
	player.Coins += coins
	p.dao.updateCoins(userId, coins)
}
func (p *PlayerLogic) UpdateLiXianShouYi(userId string, time int64) {
	err := p.dao.updateLastShouRuTime(userId, time)
	if err != nil {
		log.Error("error msg is %v", err)
	}
}
func (p *PlayerLogic) UpdateXuanChuanTilI(userId string, chuanTiLI int) error {
	return p.dao.updateXuanChuanTiLi(userId, chuanTiLI)
}
func (p *PlayerLogic) JoinUnion(userId string, unionId int32) error {
	return p.dao.joinUnion(userId, unionId)
}
func (p *PlayerLogic) UpdateUserShouChong(userId string, shouChong []ShouChong) error {
	return p.dao.updateUserShouChong(userId, shouChong)
}
